<template>
  <div class="_pt-7 _pr-10 _pl-10 taskList" @click="openTaskModal">
    <a-icon type="cloud-download" style="font-size: 24px;color:#777;" />

    <a-modal
      title="任务中心"
      :visible="taskVisible"
      :footer="false"
      :centered="true"
      :bodyStyle="{ padding: '0 20px' }"
      width="950px"
      @cancel="closeTaskModal"
    >
      <!-- <a-tabs v-model="currentTab">
        <a-tab-pane v-for="item in tabsList" :key="item.value" :tab="item.label"></a-tab-pane>
      </a-tabs> -->
      <div class="_pt-10 _pb-15">
        <a-form layout="inline">
          <a-form-item label="关键词">
            <a-input v-model="queryParam.keyword" allowClear placeholder="请输入任务名称查询"></a-input>
          </a-form-item>
          <a-form-item label="操作类型">
            <a-select placeholder="请选择" v-model="queryParam.taskType" allowClear style="width: 100px">
              <a-select-option value="EXPORT"> 导出 </a-select-option>
              <a-select-option value="IMPORT"> 导入 </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="状态">
            <a-select placeholder="请选择" v-model="queryParam.exportStatus" allowClear style="width: 100px">
              <a-select-option value="FINISHED"> 已完成 </a-select-option>
              <a-select-option value="TASK_FAIL"> 失败 </a-select-option>
              <a-select-option value="PROCESSING"> 进行中 </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <span class="table-page-search-submitButtons">
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button class="_ml-8" @click="handleReset">重置</a-button>
            </span>
          </a-form-item>
        </a-form>
      </div>
      <STable ref="taskTable" size="default" rowKey="id" :columns="columns" :data="loadData">
        <!-- 类型 -->
        <span slot="taskType" slot-scope="text, record">
          {{ record.taskType === 'EXPORT' ? '导出' : '导入' }}
        </span>
        <!-- 成功数/全部 -->
        <span slot="fileNumber" slot-scope="text, record">
          {{ record.successNumber || 0 }} / {{ record.recordsNumber || 0 }}
          <!-- 文件数 -->
          <!-- {{ record.exportTaskFileList | successTotal }} / {{ record.fileNumber }} -->
        </span>
        <!-- 状态 -->
        <span slot="exportStatus" slot-scope="text, record">
          <a-tag v-if="record.exportStatus === 'FINISHED'" color="#108ee9">已完成</a-tag>
          <a-tag v-if="record.exportStatus === 'TASK_FAIL'" color="#f50">失败</a-tag>
          <a-tag v-if="record.exportStatus === 'PROCESSING' || record.exportStatus === 'CREATED'" color="#87d068"
            >进行中</a-tag
          >
        </span>
        <span slot="action" slot-scope="text, record">
          <a-popover
            v-if="record.exportTaskFileList.length && record.exportTaskFileList.length > 1"
            title="可下载文件列表"
          >
            <template slot="content">
              <div v-for="(file, index) in record.exportTaskFileList" :key="index">
                <a :href="`${file.fileUrl}?attname=${file.fileName}.xls`">{{ file.fileName }}</a>
              </div>
              <div class="fz-12 _pt-5" style="color: red;">当不支持一键下载多文件时,请点击上列文件进行下载</div>
            </template>
            <a-button
              type="primary"
              ghost
              size="small"
              :disabled="record.exportStatus === 'PROCESSING' || record.exportStatus === 'CREATED'"
              class="_mr-5"
              @click="downloadExcel(record)"
            >
              {{ record.exportStatus === 'PROCESSING' || record.exportStatus === 'CREATED' ? '加载中...' : '下载' }}
            </a-button>
          </a-popover>
          <a-button
            v-else-if="
              record.exportTaskFileList.length ||
                record.exportStatus === 'PROCESSING' ||
                record.exportStatus === 'CREATED'
            "
            type="primary"
            ghost
            size="small"
            :disabled="record.exportStatus === 'PROCESSING' || record.exportStatus === 'CREATED'"
            class="_mr-5"
            @click="downloadExcel(record)"
          >
            {{ record.exportStatus === 'PROCESSING' || record.exportStatus === 'CREATED' ? '加载中...' : '下载' }}
          </a-button>
          <span v-else>-</span>
        </span>
      </STable>
    </a-modal>
  </div>
</template>

<script>
import STable from '@/components/Table'
import { mapGetters, mapMutations } from 'vuex'
import { getTaskList } from '@/api/common'
import { differenceBy } from 'lodash-es'

export default {
  components: {
    STable
  },
  computed: {
    ...mapGetters(['taskVisible', 'taskQueuesList'])
  },
  watch: {
    taskVisible(nval) {
      nval && this.$refs.taskTable && this.$refs.taskTable.refresh(true)
    },
    // 任务队列监听,判断列表是否需要更新,任务完成后,更新后删除队列中的任务
    taskQueuesList: {
      handler(nval) {
        if (this.taskVisible && this.$refs.taskTable) {
          nval.forEach(v => {
            this.$refs.taskTable.localDataSource.forEach(item => {
              if (v.taskId === item.taskId) {
                item.exportStatus = v.exportStatus
                item.exportTaskFileList = v.exportTaskFileList
                if (item.exportStatus !== 'PROCESSING' && item.exportStatus !== 'CREATED') {
                  // 加载完成并且已刷新列表
                  this.$store.dispatch('SetTaskQueuesList', differenceBy(nval, [item], 'taskId'))
                }
              }
            })
          })
        }
      },
      immediate: true,
      deep: true
    }
  },
  data() {
    return {
      tabsList: [
        {
          label: '活动报名',
          value: 1
        }
      ],
      currentTab: 1,
      queryParam: {
        current: 1,
        size: 10,
        keyword: '',
        taskType: undefined,
        exportStatus: undefined
      },
      columns: [
        {
          title: '发生时间',
          dataIndex: 'createTime',
          width: '180px'
        },
        {
          title: '任务列表',
          dataIndex: 'taskName',
          width: '250px',
          ellipsis: true
        },
        {
          title: '操作类型',
          dataIndex: 'taskType',
          width: '120px',
          scopedSlots: {
            customRender: 'taskType'
          }
        },
        {
          title: '成功数/全部',
          dataIndex: 'fileNumber',
          width: '120px',
          scopedSlots: {
            customRender: 'fileNumber'
          }
        },
        {
          title: '状态',
          dataIndex: 'exportStatus',
          width: '100px',
          scopedSlots: {
            customRender: 'exportStatus'
          }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          width: '150px',
          ellipsis: true
        },
        {
          title: '操作',
          dataIndex: 'action',
          fixed: 'right',
          width: '90px',
          scopedSlots: {
            customRender: 'action'
          }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.queryParam.current = parameter.pageNum
        this.queryParam.size = parameter.pageSize
        return getTaskList(this.queryParam)
      }
    }
  },
  methods: {
    ...mapMutations(['SET_TASKOVERLAY']),
    handleSearch() {
      this.$refs.taskTable.refresh(true)
    },
    handleReset() {
      Object.assign(this.$data.queryParam, this.$options.data().queryParam)
      this.$refs.taskTable.refresh(true)
    },
    openTaskModal() {
      this.$store.dispatch('ToggleTaskVisible', true)
    },
    closeTaskModal() {
      this.$store.dispatch('ToggleTaskVisible', false)
      this.SET_TASKOVERLAY(false)
    },
    downloadExcel(row) {
      row.exportTaskFileList.forEach((item, index) => {
        this.createIFrame(
          `${item.fileUrl}?attname=${item.fileName.replace(/[\s"'/\\*?<>:|~%#$&!()]/g, '_')}.xls`,
          index * 100,
          1000
        )
      })
    },
    createIFrame(url, triggerDelay, removeDelay) {
      //动态添加iframe，设置src，然后删除
      setTimeout(function() {
        var frame = document.createElement('iframe')
        frame.src = url
        frame.style.display = 'none'
        document.body.appendChild(frame)
        setTimeout(function() {
          frame.remove()
        }, removeDelay)
      }, triggerDelay)
    }
  },
  filters: {
    successTotal(list) {
      return list.filter(v => v.fileUrl).length
    }
  }
}
</script>

<style lang="less" scoped>
.taskList:hover {
  background: rgba(0, 0, 0, 0.025);
}
</style>
